package com.aismy.admin.utils;

import com.aismy.admin.exception.UnauthorizedException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

public class SecurityUtils {
    
    public static Long getUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new UnauthorizedException("未登录");
        }
        
        HttpServletRequest request = attributes.getRequest();
        Object userId = request.getAttribute("userId");
        
        if (userId == null) {
            throw new UnauthorizedException("未登录");
        }
        
        return (Long) userId;
    }

    public static String getUserRole() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new UnauthorizedException("未登录");
        }

        HttpServletRequest request = attributes.getRequest();
        Object userRole = request.getAttribute("role");

        if (userRole == null) {
            throw new UnauthorizedException("未登录");
        }

        return (String) userRole;
    }
} 